﻿using ProcessLib.Ratp.Easy.Extension;
using ProcessLib.Ratp.Easy.Select;
using ProcessLib.Ratp.Page.Processors;
using ProcessLib.Ratp.Page.Region;
using StyleSharp.Styles;

namespace ProcessLib.Ratp.Easy.Breaker;

public class XAndFFBreaker
{
    public static List<SemanticParagraph> Breaker(List<LineRegion> regions,StyleNode styleNode)
    {
        var paragraphs = new List<SemanticParagraph>();
        var lastff = "";
        var lastx = "";
        double lastbt = 0;
        var semanticParagraph = new SemanticParagraph();
        foreach (var region in regions)
        {
            var node = DivHelpSelector.Select(region.Div, "div");
            var nstr = node.GetAttribute("class");
            var x = Extractor.ExtractorX(nstr);
            var ff = Extractor.ExtractorFontFamily(nstr);
            var key = Extractor.ExtractorY(nstr)??"";
            var btt = styleNode.Bottoms.TryGetValue(key, out var btn);
            double bt = 0;
            if (btt) bt = btn??0;
            if (ff != lastff)
            {
                // ff break;
                if (semanticParagraph.LineRegions.Count > 0)
                {
                    paragraphs.Add(semanticParagraph);
                    semanticParagraph = new SemanticParagraph();
                    semanticParagraph.LineRegions.Add(region);
                    semanticParagraph.FontFamily = ff;
                    lastff = ff;
                    lastx = x;
                    lastbt = bt;
                    continue;
                }
            }

            if (x != lastx)
            {
                semanticParagraph.x++;
                if (semanticParagraph.x >= 2||Math.Abs(lastbt-bt)>20)
                {
                    if (semanticParagraph.LineRegions.Count > 0)
                    {
                        paragraphs.Add(semanticParagraph);
                        semanticParagraph = new SemanticParagraph();
                        semanticParagraph.LineRegions.Add(region);
                        semanticParagraph.FontFamily = ff;
                        lastff = ff;
                        lastx = x;
                        lastbt = bt;
                        continue;
                    }
                }
            }
            lastff = ff;
            lastx = x;
            lastbt = bt;
            semanticParagraph.LineRegions.Add(region);
        }

        return paragraphs;
    }
}